<template>
  <div class="col-span-1 p-[5px]">
    <div class="flex justify-between items-center flex-wrap mb-[25px]">
      <h1 class="mb-[0]">问题列表</h1>
      <div class="flex">
        <SvgIcon
          name="sidebar_left"
          title="收起侧栏"
          color="#817f7b"
          class="header-icon leading-[0px]"
          @click="foldChatSidebar(true)"
        />
        <SearchOutlined class="header-icon mx-[15px]" />
      </div>
    </div>
    <div class="flex justify-center">
      <a-button class="w-[90%] h-[38px]" @click="newBuiltQuestion">
        <AppstoreAddOutlined /><span>新建会话</span>
      </a-button>
    </div>
    <a-divider class="my-[16px]" />
    <div v-for="session in sessions" :key="session.id">
      <div
        class="session-item cursor-pointer mt-[2px]"
        :class="{ active: currentSession?.id === session.id }"
        @click="selectSession(session)"
      >
        {{ session.session_name }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, defineAsyncComponent, onMounted } from 'vue';
  import { AppstoreAddOutlined, SearchOutlined } from '@ant-design/icons-vue';
  import { useChatBoxStore } from '@/store/chat';
  import { useChatApi } from '@/api/chat';

  interface Session {
    id: number;
    create_time: string;
    thread_id: string;
    session_name: string;
  }

  const SvgIcon = defineAsyncComponent(
    () => import('@/components/SvgIcon/index.vue'),
  );

  const chatApi = useChatApi();
  const chatBoxStore = useChatBoxStore();

  const sessions = ref<Session[]>([]);
  const currentSession = ref<Session | null>(sessions.value[0]);

  const selectSession = (session: Session) => {
    currentSession.value = session;
  };

  const newBuiltQuestion = async () => {
    try {
      await chatApi.addQuestion({});
      await getQuestionList();
    } catch (error) {
      console.error('创建新问题失败:', error);
    }
  };

  const getQuestionList = async () => {
    try {
      const { data } = await chatApi.getQuestions({});
      sessions.value = data.list || [];
    } catch (error) {
      console.error('获取问题列表失败:', error);
    }
  };

  const foldChatSidebar = (collapsed: boolean) => {
    chatBoxStore.updataCollapsed(collapsed);
  };

  onMounted(() => {
    getQuestionList();
  });
</script>

<style scoped lang="scss">
  .session-item {
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 9px 8px;
    font-size: 14px;
    line-height: 22px;
    color: var(--text-text_primary);
  }

  .session-item:hover {
    background-color: #e5e5e5;
    border-radius: 6px;
  }

  .active {
    background-color: #e5e5e5;
    border-radius: 6px;
  }

  .header-icon {
    color: #817f7b;
    font-size: 20px;
    cursor: pointer;
    &:hover {
      color: #000;
    }
  }
</style>
